import { GoodsInfo, Sku, Spec } from '@/types/good'
import bwPowerSet from './power-set'
interface IPathMap {
  [key: string]: string[]
}
const spliter = '🤣'
export const getPathMap = (skus: Sku[]) => {
  const pathMap: IPathMap = {}
  const filterSkus = skus.filter((sku) => sku.inventory > 0)
  filterSkus.forEach((sku) => {
    const arr = sku.specs.map((spec) => spec.valueName)
    const powerSet = bwPowerSet(arr)
    powerSet.forEach((set) => {
      const key = set.join(spliter)
      if (pathMap[key]) {
        pathMap[key].push(sku.id)
      } else {
        pathMap[key] = [sku.id]
      }
    })
  })
  return pathMap
}
export const getSelectedSpec = (specs: Spec[]) => {
  const arr: (string | undefined)[] = []
  specs.forEach((spec) => {
    const btnObj = spec.values.find((btnObj) => btnObj.selected)
    arr.push(btnObj?.name)
  })
  return arr
}

export const updateDisabledStatus = (specs: Spec[], pathMap: IPathMap) => {
  specs.forEach((spec, i) => {
    spec.values.forEach((btnObj) => {
      if (btnObj.selected) return
      const originSelectedBtnName = getSelectedSpec(specs)
      originSelectedBtnName[i] = btnObj.name
      const key = originSelectedBtnName.filter((v) => v).join(spliter)
      if (pathMap[key]) {
        btnObj.disabled = false
      } else {
        btnObj.disabled = true
      }
    })
  })
}
export const initDefaultSelected = (goods: GoodsInfo, skuId: string | undefined) => {
  if (!skuId) return
  // 根据 skuId 找到那一项 sku
  const sku = goods.skus.find((sku) => sku.id === skuId)
  if (!sku) return
  goods.specs.forEach((spec, i) => {
    spec.values.forEach((btnObj) => {
      // 看一下找到 sku 里面对应的行的 valueName，如果等于按钮的 name，就选中
      btnObj.selected = sku.specs[i].valueName === btnObj.name
    })
  })
}
